<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贾维斯智能AI小助手(v1.1)</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 20px;
        }
        .chat-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        h1 {
            color: #2c3e50;
            margin-top: 0;
            text-align: center;
            grid-column: 1 / -1;
        }
        .chat-history {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
            height: 500px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        .message {
            padding: 15px;
            border-radius: 10px;
            max-width: 80%;
        }
        .user-message {
            background: #3498db;
            color: white;
            align-self: flex-end;
            margin-left: auto;
        }
        .ai-message {
            background: #ecf0f1;
            color: #2c3e50;
            border: 1px solid #bdc3c7;
        }
        .input-area {
            display: flex;
            gap: 10px;
            align-items: center;
            padding: 15px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        #prompt {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #bdc3c7;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }
        #prompt:focus {
            border-color: #3498db;
        }
        button {
            padding: 12px 25px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background: #2980b9;
        }
        .info-panel {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
            height: 500px;
            overflow-y: auto;
        }
        .info-section {
            margin-bottom: 20px;
        }
        .info-title {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 8px;
            font-size: 18px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
        }
        .info-item {
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
        }
        .info-label {
            color: #7f8c8d;
            font-weight: 500;
        }
        .info-value {
            color: #2c3e50;
            font-weight: normal;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-style: italic;
        }
        .error {
            color: #e74c3c;
            font-weight: bold;
        }
        @media (max-width: 768px) {
            .container {
                grid-template-columns: 1fr;
            }
            .info-panel {
                order: -1;
                height: 200px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h1>💬 贾维斯智能AI小助手(v1.1)</h1>

    <div class="chat-container">
        <div class="chat-history" id="chat-history">
            <div class="message ai-message">
                你好！我是贾维斯智能AI小助手，有什么我可以帮助你的吗？
            </div>
        </div>

        <div class="input-area">
            <input type="text" id="prompt" placeholder="请输入您的问题...">
            <button onclick="sendChat()">发送</button>
        </div>
    </div>

    <div class="info-panel">
        <div class="info-section">
            <div class="info-title">模型信息</div>
            <div class="info-item">
                <span class="info-label">模型名称:</span>
                <span class="info-value" id="model-name">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">创建时间:</span>
                <span class="info-value" id="created-at">-</span>
            </div>
        </div>

        <div class="info-section">
            <div class="info-title">状态信息</div>
            <div class="info-item">
                <span class="info-label">完成状态:</span>
                <span class="info-value" id="done-status">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">完成原因:</span>
                <span class="info-value" id="done-reason">-</span>
            </div>
        </div>

        <div class="info-section">
            <div class="info-title">性能指标</div>
            <div class="info-item">
                <span class="info-label">总耗时:</span>
                <span class="info-value" id="total-duration">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">模型加载耗时:</span>
                <span class="info-value" id="load-duration">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">prompt token 数量:</span>
                <span class="info-value" id="prompt-eval-count">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">prompt 评估耗时:</span>
                <span class="info-value" id="prompt-eval-duration">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">推理 token 数量:</span>
                <span class="info-value" id="eval-count">-</span>
            </div>
            <div class="info-item">
                <span class="info-label">推理阶段耗时:</span>
                <span class="info-value" id="eval-duration">-</span>
            </div>
        </div>
    </div>
</div>

<script>
    // 格式化时间戳
    function formatTimestamp(timestamp) {
        if (!timestamp) return '-';
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }

    // 格式化时长（纳秒转换为毫秒或秒）
    function formatDuration(nanos) {
        if (!nanos) return '-';
        if (nanos < 1000000) {
            return `${nanos} ns`;
        } else if (nanos < 1000000000) {
            return `${(nanos / 1000000).toFixed(2)} ms`;
        } else {
            return `${(nanos / 1000000000).toFixed(2)} s`;
        }
    }

    // 添加消息到聊天历史
    function addMessage(text, isUser) {
        const chatHistory = document.getElementById('chat-history');
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message');
        messageDiv.classList.add(isUser ? 'user-message' : 'ai-message');
        messageDiv.textContent = text;
        chatHistory.appendChild(messageDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }

    // 更新信息面板
    function updateInfoPanel(data) {
        document.getElementById('model-name').textContent = data.model || '-';
        document.getElementById('created-at').textContent = formatTimestamp(data.created_at);
        document.getElementById('done-status').textContent = data.done ? '已完成' : '处理中';
        document.getElementById('done-reason').textContent = data.done_reason || '-';
        document.getElementById('total-duration').textContent = formatDuration(data.total_duration);
        document.getElementById('load-duration').textContent = formatDuration(data.load_duration);
        document.getElementById('prompt-eval-count').textContent = data.prompt_eval_count || '-';
        document.getElementById('prompt-eval-duration').textContent = formatDuration(data.prompt_eval_duration);
        document.getElementById('eval-count').textContent = data.eval_count || '-';
        document.getElementById('eval-duration').textContent = formatDuration(data.eval_duration);
    }

    // 清空信息面板
    function clearInfoPanel() {
        updateInfoPanel({});
    }

    async function sendChat() {
        const prompt = document.getElementById('prompt').value;
        if (!prompt.trim()) return;

        // 清空输入框
        document.getElementById('prompt').value = '';

        // 添加用户消息
        addMessage(prompt, true);

        // 清空信息面板并显示加载状态
        clearInfoPanel();
        addMessage('正在思考...', false);

        try {
            const res = await fetch('/api/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: prompt }) // 使用message字段，与后端一致
            });

            if (!res.ok) {
                throw new Error(`服务器错误: ${res.status}`);
            }

            // 移除加载消息
            const chatHistory = document.getElementById('chat-history');
            chatHistory.removeChild(chatHistory.lastChild);

            // 解析响应
            const responseText = await res.text();
            let data;

            try {
                // 尝试解析JSON
                data = JSON.parse(responseText);
            } catch (e) {
                // 如果不是有效的JSON，作为普通文本处理
                addMessage(responseText, false);
                return;
            }

            // 更新信息面板
            updateInfoPanel(data);

            // 添加AI回复到聊天历史（重点展示）
            let aiReply = '';
            if (data.message && data.message.content) {
                aiReply = data.message.content;
            } else if (data.reply) {
                aiReply = data.reply;
            } else {
                aiReply = JSON.stringify(data);
            }

            addMessage(aiReply, false);

        } catch (error) {
            // 移除加载消息
            const chatHistory = document.getElementById('chat-history');
            chatHistory.removeChild(chatHistory.lastChild);

            // 显示错误消息
            addMessage(`错误: ${error.message}`, false);
        }
    }

    // 添加键盘事件监听（按Enter发送消息）
    document.getElementById('prompt').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendChat();
        }
    });
</script>
</body>
</html>